package com.bw.home.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.widget.ImageViewCompat
import androidx.core.widget.NestedScrollView
import androidx.core.widget.NestedScrollView.OnScrollChangeListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bw.common.utils.LogUtils
import com.bw.home.R
import com.bw.home.databinding.FragmentHomeBinding
import com.bw.home.databinding.ItemSimplevideoBinding
import com.bw.home.intent.SimpleTypeIntent
import com.bw.home.intent.SimpleVideoIntent
import com.bw.home.model.entity.SimpleTypeEntity
import com.bw.home.model.entity.SimpleVideoEntity
import com.bw.home.model.service.SimpleTypeModel
import com.bw.home.model.service.SimpleVideoModel
import com.bw.home.state.SimpleTypeState
import com.bw.home.state.SimpleVideoState
import com.bw.home.widget.TitleBar
import com.bw.imageloader.ImageLoaderManager
import com.bw.imageloader.ImageOptions
import com.bw.mvicore.ui.BaseMVIFragment
import com.google.android.material.tabs.TabLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @author:created by hahajing
 * 时间：2024/4/24 0024
 * 企鹅号:444511958
 * 描述:
 */
class HomeFragment : BaseMVIFragment() {
    private val TAG = HomeFragment::class.java.simpleName
    private lateinit var simpleVideoModel: SimpleVideoModel
    private lateinit var simpleTypeModel: SimpleTypeModel
    private var page: Int = 0
    private val pageSize: Int = 10
    private var currentType:String = ""
    private lateinit var binding: FragmentHomeBinding
    private lateinit var adapter: SimpleVideoAdapter
    override fun generateModel() {
        simpleVideoModel = ViewModelProviders.of(this).get(SimpleVideoModel::class.java)
        simpleTypeModel = ViewModelProviders.of(this).get(SimpleTypeModel::class.java)
    }

    override fun initEvent() {
        /**
         * 搜索框的点击
         */
        binding.tbHomeTitlebar.setOnClickListener(object : TitleBar.OnClickListener {
            override fun onClick(view: View?) {
                getBaseActivity().route(SearchActivity::class.java)
            }
        })

        /**
         * Simple类别tab切换事件
         */
        binding.tabHomeType.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                //类别被切换
                typeIsChanged=true
                if (tab?.tag!=null){
                    val entity = tab?.tag as SimpleTypeEntity
                    currentType=entity.channelid
                    page=0
                    generateLifeCycleLaunch {
                        loadSimpleVideoByChannelId()
                    }

                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })

        /**
         * 列表的下拉刷新
         */
        binding.srlHomeRefresh.setOnRefreshListener(object :OnRefreshListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page=0
                generateLifeCycleLaunch {
                    loadSimpleVideoByChannelId()
                }
                binding.srlHomeRefresh.finishRefresh()
            }

        })

        /**
         * 列表的上拉加载分页数据
         */
        binding.srlHomeRefresh.setOnLoadMoreListener {
            page++
            generateLifeCycleLaunch {
                loadSimpleVideoByChannelId()
            }
            binding.srlHomeRefresh.finishLoadMore()
        }

        binding.nsvHome.setOnScrollChangeListener(object :OnScrollChangeListener{
            override fun onScrollChange(
                v: NestedScrollView,
                scrollX: Int,
                scrollY: Int,
                oldScrollX: Int,
                oldScrollY: Int
            ) {
                LogUtils.d(TAG,"scrollY = ${scrollY} oldScrollY = ${oldScrollY}")
                setUpVisibility(scrollY)
            }

        })

        binding.ivHomeUp.setOnClickListener{
            binding.nsvHome.scrollTo(0,0)
        }

    }

    private var typeIsChanged:Boolean = false


    override fun generateFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun initView() {
        super.initView()
        binding.rvHomeSimplevideo.layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
        adapter = SimpleVideoAdapter()
        binding.rvHomeSimplevideo.adapter = adapter
    }

    private fun setUpVisibility(scrollY: Int) {
        LogUtils.d(TAG,"setUpVisibility method exec....")
        if (scrollY>400){
            LogUtils.d(TAG,"> 400")
            binding.ivHomeUp.visibility=View.VISIBLE
        }
        else{
            LogUtils.d(TAG,"<400")
            binding.ivHomeUp.visibility=View.GONE
        }
    }

    override fun lazyLoad() {
        generateLifeCycleLaunch {

            simpleTypeModel.intents.send(SimpleTypeIntent.GetSimpleTypeIntent)
        }
    }

    override fun handleState() {
        generateLifeCycleLaunch {
            simpleVideoModel.state.collect {
                when (it) {
                    is SimpleVideoState.SimpleVideoDefaultState -> {}
                    is SimpleVideoState.GetSimpleVideoSuccessState -> {
                        if (typeIsChanged){
                            adapter.refreshData(it.datas,true)
                        }else{
                            adapter.refreshData(it.datas)
                        }

                        typeIsChanged=false

                    }

                    is SimpleVideoState.GetSimpleVideoFailedState -> {
                        showMsg(resources.getString(it.throwable.message.let { it!!.toInt() }))
                    }
                }

            }
        }

        generateLifeCycleLaunch {
            simpleTypeModel.state.collect {
                when (it) {
                    is SimpleTypeState.SimpleTypeDefaultState -> {}
                    is SimpleTypeState.GetSimpleTypeSuceessState -> {
                        LogUtils.d(TAG, "do execute GetSimpleTypeSuceessState")
                        generateTabLayout(it.types)
                        currentType=it.types.get(0).channelid
                        loadSimpleVideoByChannelId()
                    }

                    is SimpleTypeState.GetSimpleTypeFailedState -> {
                        withContext(Dispatchers.Main) {
                            showMsg(getResFromStringId(R.string.simpletype_getdata_failed))
                        }
                    }
                }
            }
        }
    }

    private suspend fun loadSimpleVideoByChannelId() {
        //获取到Simple类型后发送列表请求
        simpleVideoModel.intents.send(SimpleVideoIntent.GetSimpleDataIntent(currentType,page, pageSize))
    }

    /**
     * 构建tabs
     */
    private fun generateTabLayout(types: List<SimpleTypeEntity>) {
        types.forEach {
            LogUtils.d(TAG, "${it.typename}")
            val tab = binding.tabHomeType.newTab()
            tab.setText(it.typename)
            tab.tag=it
            binding.tabHomeType.addTab(tab)
        }
    }

    inner class SimpleVideoAdapter() : RecyclerView.Adapter<SimpleVideoAdapter.SimpleVideoViewHolder>() {
        private var data: MutableList<SimpleVideoEntity> = mutableListOf()

        /**
         * 刷新数据方法
         */
        fun refreshData(_data: List<SimpleVideoEntity>,isClean:Boolean=false) {
            if (isClean){
                data.clear()
            }
            data.addAll(_data)
            this.notifyDataSetChanged()
        }

        inner class SimpleVideoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val subBinding: ItemSimplevideoBinding = ItemSimplevideoBinding.bind(view)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleVideoViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_simplevideo, parent, false)
            return SimpleVideoViewHolder(view)
        }

        override fun getItemCount(): Int {
            return data.size
        }

        override fun onBindViewHolder(holder: SimpleVideoViewHolder, position: Int) {
            val entity = data.get(position)
            holder.subBinding.tvHomeItemSimplevideoDescription.text = entity.description.trim()
            holder.subBinding.tvHomeItemSimplevideoName.text = entity.name
            val options: ImageOptions = ImageOptions.Builder()
                .setPlaceImage(com.bw.common.R.mipmap.ic_launcher)
                .build()
            ImageLoaderManager.getInstance().loadFileIntoImageView(
                context!!,
                entity.avatar_url,
                holder.subBinding.ivHomeItemSimplevideoAuthorimg,
                options
            )
            ImageLoaderManager.getInstance().loadFileIntoImageView(
                context!!,
                entity.videomainimag,
                holder.subBinding.ivHomeItemSimplevideoVideomainimg,
                options
            )

            holder.subBinding.ivHomeItemSimplevideoVideomainimg.setOnClickListener(object :View.OnClickListener{
                override fun onClick(v: View?) {
                    val bundle:Bundle = Bundle()
                    bundle.putParcelable("entity",entity)
                    getBaseActivity().route(DetailActivity::class.java,bundle)
                }

            })
        }

        override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
            super.onAttachedToRecyclerView(recyclerView)
            recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        Glide.with(context!!).resumeRequests()
                    } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING || newState == RecyclerView.SCROLL_STATE_SETTLING) {
                        Glide.with(context!!).pauseAllRequests()
                    }
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                }
            })
        }
    }
}